/** ============================================================================================== **/
/**						TANK MANAGER											 				   **/	
/** ============================================================================================== **/

BootApplication.controller("MyTankController",
			[ "$scope", "$rootScope", '$translate', "NgTableParams", "MyTankService", '$http', 'configuration', "LoadingAppService", "$mdDialog",
	 function ($scope, 	 $rootScope,   $translate,   NgTableParams,   myTankService,   $http,   configuration,   LoadingAppService,   $mdDialog) {
	
	/** INIZIALIZZAZIONI ************************************************************************************************************************/
	$scope.tankList						= [];
	$scope.filtriAttivi					= {};
	$scope.displayProp					= {};
	$scope.isEdit						= false;
	$scope.tankModel					= {};
	$scope.tankTempModel				= {};
    $scope.errorMessage					= "";
    $scope.showTank						= true;
    $scope.showBtnNewTank				= true;
    $scope.isDetail						= false;
    $scope.isNewTask					= false;
    
    $scope.hsValoriVasca				= false;
    $scope.hsTasks						= false;
    $scope.hsLivestock					= false;
    $scope.hsTankAnalisys				= false;
	/********************************************************************************************************************************************/
	
	/*************************************************************************************************	FIGURE VIEW		   ***********	START   */
	$scope.bigCurrentPage 				= 1;
	$scope.itemsPerPage 				= 8;
	$scope.maxSize 						= 5;
	
	$scope.$watch('idUser', function() {
		if ($rootScope.idUser!=undefined) {
			var sPageURL 		= decodeURIComponent(window.location.search.substring(1)), sURLVariables = sPageURL.split('&'), sParameterName, i;
			sParameterName 		= sURLVariables[0].split('=');
			$rootScope.tankId 	= sParameterName[1];
			$scope.tankId 		= sParameterName[1];
			
			if ( $rootScope.tankId!=undefined) {
				myTankService.getTank( $rootScope.tankId ).then(function( response ){
					if (response!=null && response.data.success && response.data.aaData!=null) {
						$scope.activeDetailTank( response.data.aaData[0] );
					}
				});
			} else
				$scope.getTankList();
		}
    });
	
	$scope.getTankList = function () {
		console.log("my-tank-ctrl.js		>>>	Recupero la lista delle vasche");
		LoadingAppService.showLoader("Caricamento lista");
		$scope.showTankList					= false;
		$scope.tankList						= [];
		$scope.bigTotalItems				= 0;
		$scope.filtriAttivi.userId			= $rootScope.idUser;
		$scope.displayProp.paginate			= true;
		$scope.displayProp.displayStart		= $scope.bigCurrentPage==1 ? 0 : $scope.itemsPerPage*($scope.bigCurrentPage-1);
		$scope.displayProp.displayLength	= $scope.itemsPerPage;
		myTankService.getTankList( $scope.filtriAttivi, $scope.displayProp ).then(function( response ){
			if (response!=null && response.data!=null && response.data.aaData!=null) {
				$scope.tankList			= response.data.aaData;
				if ( $scope.tankList.length<4 ) {
					/** L'utente puo' aggiungere altre vasche **/
					$scope.showBtnNewTank	= true;
				} else {
					/** L'utente ha raggiunto il massimo delle vasche consentite **/
					$scope.showBtnNewTank	= false;
				}
				$scope.bigTotalItems 	= response.data.iTotalRecords;
				LoadingAppService.hideLoader();
				$scope.showTankList					= true;
			}
		});
	}
	
	$scope.setPage = function (pageNo) {
		$scope.bigCurrentPage = pageNo;
		$scope.getTankList();
	};
	$scope.pageChanged = function() {
		$scope.getTankList();
	};
	
	$scope.activeNewTank = function(event){
		event.preventDefault();
		$scope.tankModel		= {};					//Vasca selezionata
		$scope.tankTempModel	= {};					//Vasca temporanea selezionata
		$scope.showTank			= false;				//visualizza elenco vasche
		$scope.showDetailTank	= false;				//visualizza dettaglio vasca
		$scope.isDetail			= false;				//sono nel dettaglio
		$scope.showNewTank		= true;					//visualizza nuova vasca
	}
	
	$scope.activeDetailTank = function( tank){
		event.preventDefault();
		$scope.tankModel		= tank;					//Vasca selezionata
		$scope.tankTempModel	= $scope.tankModel;		//Vasca temporanea selezionata
		$rootScope.tankId		= tank.id;	//Salvo nel rootScope la vasca
		$scope.showTank			= false;				//visualizza elenco vasche
		$scope.showDetailTank	= true;					//visualizza dettaglio vasca
		$scope.isDetail			= true;					//sono nel dettaglio
		$scope.showNewTank		= false;				//visualizza nuova vasca
		/*Recupero dettagli vasca*/
		$scope.getTask();								//recupero task
		$scope.getLivestock();							//recupero livestock
		$scope.getTankAnalisys();						//recupero tank analisys
		$scope.getSocialNetwork();						//recupero social networks
	}
	
	$scope.returnTanks = function(event){
		event.preventDefault();
		$scope.tankModel		= {};
		$scope.showTank			= true;
		$scope.showDetailTank	= false;
		$scope.showNewTank		= false;
		$scope.isDetail			= false;
		$scope.getTankList();
	}
	
	$scope.fhsValoriVasca = function (){
		$scope.hsValoriVasca				= !$scope.hsValoriVasca;
	    $scope.hsTasks						= false;
	    $scope.hsLivestock					= false;
	    $scope.hsTankAnalisys				= false;
	}
	$scope.fhsTasks = function (){
		$scope.hsValoriVasca				= false;
	    $scope.hsTasks						= !$scope.hsTasks;
	    $scope.hsLivestock					= false;
	    $scope.hsTankAnalisys				= false;
	}
	$scope.fhsLivestock = function (){
		$scope.hsValoriVasca				= false;
	    $scope.hsTasks						= false;
	    $scope.hsLivestock					= !$scope.hsLivestock;
	    $scope.hsTankAnalisys				= false;
	}
	$scope.fhsTankAnalisys = function (){
		$scope.hsValoriVasca				= false;
	    $scope.hsTasks						= false;
	    $scope.hsLivestock					= false;
	    $scope.hsTankAnalisys				= !$scope.hsTankAnalisys;
	}
	/******************************************************************************************	FIGURE VIEW		   ***********	END     **/
	
	/******************************************************************************************	GESTIONE MODIFICHE  ***********	START   **/
    $scope.saveTank = function ( event ) {
    	console.log("my-tank-ctrl.js		>>>	salva modifiche alla vasca");
    	LoadingAppService.showLoader("Salvataggio in corso...");
		$scope.tankModel.idUser			= $rootScope.idUser;
		myTankService.saveTank( $scope.tankModel ).then(function( response ){
			if (response!=null && response.data!=null && response.data.aaData!=null) {
				console.log("my-tank-ctrl.js		>>>	La tua vasca e' stata salvata con successo");
				LoadingAppService.hideLoader();
				$scope.isEdit=false;
				$scope.returnTanks(event);
			} else {
				console.log("my-tank-ctrl.js		>>>	La tua vasca NON e' stata salvata con successo");
				LoadingAppService.hideLoader();
				$scope.isEdit=true;
			}
		});
    }
    
    $scope.modifyTank = function ( event ) {
    	console.log("my-tank-ctrl.js		>>>	inizia modifica alla vasca");
		$scope.tankModel.idUser		= $rootScope.idUser;
		$scope.isEdit				= true;
    }
    
    $scope.cancelTank = function ( event ) {
    	console.log("my-tank-ctrl.js		>>>	annulla modifiche alla vasca");
		$scope.tankModel.idUser		= $rootScope.idUser;
		$scope.isEdit				= false;
		$scope.tankModel			= $scope.tankTempModel;
    }

    $scope.deleteTank = function ( event, tank ) {
    	console.log("my-tank-ctrl.js		>>>	elimino la tua vasca");
    	LoadingAppService.showLoader("Eliminazione in corso...");
		$scope.tankModel.idUser			= tank.idUser;
    	$scope.tankModel.id				= tank.id;
		myTankService.deleteTank( $scope.tankModel ).then(function( response ){
			if (response!=null && response.data!=null && response.data.aaData!=null)
				console.log("my-tank-ctrl.js		>>>	La tua vasca e' stata eliminata con successo");
			else
				console.log("my-tank-ctrl.js		>>>	La tua vasca NON e' stata eliminata con successo");
			LoadingAppService.hideLoader();
			$scope.returnTanks(event);
		});
    }
    
    $scope.validatorTank = function ( ) {
    	var resultValidation = true;
    	/** BASE VALIDATOR **/
    	if ($scope.tankModel.nome==undefined || $scope.tankModel.nome=="") {
    		$scope.errorMessage="Non e' stato definito il nome";
    		resultValidation=false;
    	} else if ($scope.tankModel.larghezza==undefined || $scope.tankModel.larghezza=="") {
    		$scope.errorMessage="Non e' stata definita la larghezza";
    		resultValidation=false;
    	} else if ($scope.tankModel.lunghezza==undefined || $scope.tankModel.lunghezza=="") {
    		$scope.errorMessage="Non e' stata definita la lunghezza";
    		resultValidation=false;
    	} else if ($scope.tankModel.altezza==undefined || $scope.tankModel.altezza=="") {
    		$scope.errorMessage="Non e' stata definita l'altezza";
    		resultValidation=false;
    	}
    	/** EXTEND VALIDATOR **/
    	if (!$.isNumeric($scope.tankModel.larghezza)) {
    		$scope.errorMessage="La larghezza non e' un numero";
    		resultValidation=false;
    	} else if (!$.isNumeric($scope.tankModel.lunghezza)) {
    		$scope.errorMessage="La lunghezza non e' un numero";
    		resultValidation=false;
    	} else if (!$.isNumeric($scope.tankModel.altezza)) {
    		$scope.errorMessage="L'altezza non e' un numero";
    		resultValidation=false;
    	}
    	return resultValidation;
    }
    
    $scope.calculateCapacity = function (){
    	if (
    			($scope.tankModel.larghezza!=undefined && $scope.tankModel.larghezza!="" && $.isNumeric($scope.tankModel.larghezza)) &&
    			($scope.tankModel.altezza!=undefined && $scope.tankModel.altezza!="" && $.isNumeric($scope.tankModel.altezza)) &&
    			($scope.tankModel.lunghezza!=undefined && $scope.tankModel.lunghezza!="" && $.isNumeric($scope.tankModel.lunghezza)) ) {
    		$scope.tankModel.capacita = $scope.tankModel.larghezza * $scope.tankModel.altezza * $scope.tankModel.lunghezza;
    		$scope.tankModel.capacita = $scope.tankModel.capacita/1000;
    	}
    }
    
    /************************/
    /** GESTIONE TASK	   **/
    /************************/
    $scope.getTask = function () {
    	console.log("my-tank-ctrl.js		>>>	recupero task vasca");
		$scope.tankModel.idUser			= $rootScope.idUser;
		$rootScope.tankId				= $scope.tankModel.id;
		$scope.tankModel.id				= $scope.tankModel.id;
		myTankService.getTask( $scope.tankModel ).then(function( response ){
			if (response!=null && response.data!=null && response.data.aaData!=null) {
				$scope.taskList				= response.data.aaData;
				$scope.bigTotalItems 		= response.data.iTotalRecords;
			} else {
				$scope.taskList		= {};
				$scope.bigTotalItems 		= 0;
			}
			LoadingAppService.hideLoader();
		});
	}
    $scope.addTask = function () {
    	console.log("my-tank-ctrl.js		>>>	aggiungi task");
    	$scope.isNewTask				= true;
    }
    
    /************************/
    /** GESTIONE LIVESTOCK **/
    /************************/
    $scope.getLivestock = function () {
    	console.log("my-tank-ctrl.js		>>>	recupero livestock vasca");
		$scope.tankModel.idUser			= $rootScope.idUser;
		$rootScope.tankId				= $scope.tankModel.id;
		$scope.tankModel.id				= $scope.tankModel.id;
		myTankService.getLivestock( $scope.tankModel ).then(function( response ){
			if (response!=null && response.data!=null && response.data.aaData!=null) {
				$scope.livestockList		= response.data.aaData;
				$scope.bigTotalItems 		= response.data.iTotalRecords;
			} else {
				$scope.livestockList		= {};
				$scope.bigTotalItems 		= 0;
			}
			LoadingAppService.hideLoader();
		});
	}
    $scope.addLivestock = function () {
    	console.log("my-tank-ctrl.js		>>>	aggiungi livestock");
    }
    $scope.deleteLivestock = function (event, livestock) {
    	console.log("my-tank-ctrl.js		>>>	elimino livestock ");
    	livestock.tankId = $scope.tankId;
    	myTankService.deleteLivestock( livestock ).then(function( response ){
			console.log("my-tank-ctrl.js		>>>	livestock eliminato con successo");
			$scope.getLivestock();
		});
    }
    
    /*****************************/
    /** GESTIONE TANK ANALISYS	**/
    /*****************************/
    $scope.getTankAnalisys = function () {
    	console.log("my-tank-ctrl.js		>>>	recupero tank analisys vasca");
		$scope.tankModel.idUser			= $rootScope.idUser;
		$rootScope.tankId				= $scope.tankModel.id;
		$scope.tankId					= $scope.tankModel.id;
		myTankService.getTankAnalisys( $scope.tankModel ).then(function( response ){
			if (response!=null && response.data!=null && response.data.aaData!=null) {
				$scope.tankAnalisysList		= response.data.aaData;
				$scope.bigTotalItems 		= response.data.iTotalRecords;
			} else {
				$scope.tankAnalisysList		= {};
				$scope.bigTotalItems 		= 0;
			}
			LoadingAppService.hideLoader();
		});
	}
    $scope.addTankAnalisys = function () {
    	console.log("my-tank-ctrl.js		>>>	aggiungi tank analisys");
    }
    
    /********************************/
    /** GESTIONE SOCIAL NETWORKS   **/
    /********************************/
    $scope.getSocialNetwork = function () {
    	console.log("my-tank-ctrl.js		>>>	recupero social networks vasca");
		$scope.tankModel.idUser			= $rootScope.idUser;
		$rootScope.tankId				= $scope.tankModel.id;
		$scope.tankModel.id				= $scope.tankModel.id;
		myTankService.getSocialNetwork( $scope.tankModel ).then(function( response ){
			if (response!=null && response.data!=null && response.data.aaData!=null) {
				$scope.socialNetList		= response.data.aaData;
				$scope.bigTotalItems 		= response.data.iTotalRecords;
			} else {
				$scope.socialNetList		= {};
				$scope.bigTotalItems 		= 0;
			}
			LoadingAppService.hideLoader();
		});
	}
    $scope.addSocialNetworks = function () {
    	console.log("my-tank-ctrl.js		>>>	aggiungi social networks");
    }
    
    /******************************************************************************************	GESTIONE MODIFICHE  ***********	END     **/
    
	/******************************************************************************************	UTILITY 		   ***********	START	**/
	$scope.showAlert = function( type, message ) {
		$mdDialog.show(
			$mdDialog.alert()
	        	.parent(angular.element(document.querySelector('#popupContainer')))
	        	.clickOutsideToClose(true)
	        	.title(type)
	        	.textContent(message)
	        	.ariaLabel('Alert Dialog Demo')
	        	.ok('OK')
	    );
	};
	/*****************************************************************************************	UTILITY 		   ***********	END		**/
}]);